# -*- coding: utf-8 -*-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：tensorflow_mnist_simple.py
#日期：2019-11-12
#备注：官方入门教程：Softmax回归模型
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import time

sTime = time.time()
mnist = input_data.read_data_sets('F:\PythonProject\Mnist', one_hot=True)    # MNIST数据集所在路径


# 实现回归模型
x = tf.placeholder(tf.float32, [None, 784])     # 输入任意数量的MNIST图像
W = tf.Variable(tf.zeros([784,10]))             # 权重W
b = tf.Variable(tf.zeros([10]))                 # 偏置b

y_ = tf.placeholder(tf.float32, [None, 10])     # 输入实际标签值


# 训练模型：成本函数“交叉熵”（cross-entropy）
y = tf.nn.softmax(tf.matmul(x,W) + b)           # 实现我们的模型
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
#train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)  # 用梯度下降算法（gradient descent algorithm）以0.01的学习速率最小化交叉熵
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)    # AdamOptimizer优化器

# 评估我们的模型
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))         # 模型对比实际
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# 创建 Saver() 对象，保存模型
saver = tf.train.Saver()

# 初始化我们创建的变量
init = tf.global_variables_initializer()

# 训练模型
with tf.Session() as sess:
    sess.run(init)
    for i in range(10000):
        batch_x, batch_y = mnist.train.next_batch(50)
        # sess.run(train_step, feed_dict={x: batch_x, y_: batch_y})
        train_step.run(feed_dict={x: batch_x, y_: batch_y})         # 等价于上面
        if i % 100 == 0:
            train_accuracy = accuracy.eval(feed_dict={x: batch_x,y_: batch_y})
            print("step %d,train accuracy %g " %(i,train_accuracy))
    # 保存模型
    saver.save(sess, 'F:\PythonProject\Mnist\model\\simple\mnist.ckpt')       # ,global_step=1000
    # 我们计算所学习到的模型在测试数据集上面的正确率
    print("test accuracy %g " % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

eTime = time.time()
s = eTime - sTime
print('花费的时间为：%.2f秒' % (s))